package cn.itrip.biz.service.impl;


import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.beans.pojo.ItripHotelRoom;
import cn.itrip.beans.pojo.ItripOrderLinkUser;
import cn.itrip.beans.vo.*;
import cn.itrip.beans.vo.tokentakevo.OrderAndLinkUserVo;
import cn.itrip.biz.service.IItripHotelOrderService;
import cn.itrip.common.Page;
import cn.itrip.dao.ItripHotelOrderMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 滕召伟
 * @since 2020-02-27
 */
@Service
public class ItripHotelOrderServiceImpl implements IItripHotelOrderService {
    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;

    /**
     * 全部订单
     *
     * @param pageNo   第几页
     * @param pageSize 每页多少行
     * @return
     */
    @Override
    public Page<ItripHotelOrder> listHotelOrder(Integer pageNo, Integer pageSize, ItripHotelOrder itripHotelOrder) {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }

        Page<ItripHotelOrder> page = new Page<>();
        List<ItripHotelOrder> list = itripHotelOrderMapper.listHotelOrder(itripHotelOrder);
        page.pageUtil(pageNo, pageSize, list);
        return page;
    }

    /**
     * 订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderRoomVo getOrderId(Long orderId) {
        try {
            if (orderId != null && !"".equals(orderId)) {
                OrderRoomVo order = itripHotelOrderMapper.getOrderId(orderId);
                Map<String, String> map = new HashMap<>();
                if (order.getOrderStatus() == 1) {
                    if (order.getOrderStatus() == 1) {
                        order.setProcessNode("3");
                    }
                    map.put("1", "订单提交");
                    map.put("2", "订单支付");
                    map.put("3", "订单取消");
                    order.setOrderProcess(map);
                    return order;
                } else {
                    if (order.getOrderStatus() == 0) {
                        order.setProcessNode("1");
                    } else if (order.getOrderStatus() == 2) {
                        order.setProcessNode("3");
                    } else if (order.getOrderStatus() == 3) {
                        order.setProcessNode("5");
                    } else if (order.getOrderStatus() == 4) {
                        order.setProcessNode("6");
                    }
                    map.put("1", "订单提交");
                    map.put("2", "订单支付");
                    map.put("3", "支付成功");
                    map.put("4", "入住");
                    map.put("5", "订单点评");
                    map.put("6", "已完成");
                    order.setOrderProcess(map);
                    return order;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 入住信息
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderRoomHotelVO getOrderRommHtoId(Long orderId) {
        try {
            if (orderId != null && !"".equals(orderId)) {
                OrderRoomHotelVO orderRoomHotelVO = itripHotelOrderMapper.getOrderRommHtoId(orderId);
                return orderRoomHotelVO;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取房型ID
     *
     * @param hotelId
     * @param orderId
     * @return
     */
    @Override
    public ItripHotelRoom getHotelId(Long hotelId, Long orderId) {
        if (hotelId != null && !"".equals(hotelId) && orderId != null && !"".equals(orderId)) {
            ItripHotelRoom room = itripHotelOrderMapper.getHotelId(hotelId, orderId);
            return room;
        }
        return null;
    }

    /**
     * 获取订单和用户
     *
     * @param Id
     * @return
     */
    @Override
    public OrderLinkUserVo getOrderLinkUserVoId(Long Id) {
        try {
            if (Id != null && !"".equals(Id)) {
                OrderLinkUserVo userVo = itripHotelOrderMapper.getOrderLinkUserVoId(Id);
                List<LinkUserAndNameVo> listLinkUserIdAndName = itripHotelOrderMapper.listLinkUserIdAndName(Id);
                userVo.setItripOrderLinkUserList(listLinkUserIdAndName);
                return userVo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询房间信息
     *
     * @param itripHotelOrder
     * @return
     */
    @Override
    public StoreOrderRommHotelVo getHotelProductStoreDic(ItripHotelOrder itripHotelOrder) {
        try {
            if (!"".equals(itripHotelOrder) && itripHotelOrder != null) {
                //时间转换 将前台传过来的时间转换成yyyy-MM-dd HH:mm:ss
                SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);//输入的被转化的时间格式
                SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//需要转化成的时间格式
                Date CheckInDate = null;
                Date CheckOutDate = null;
                try {
                    CheckInDate = dff.parse(itripHotelOrder.getCheckInDate().toString());
                    CheckOutDate = dff.parse(itripHotelOrder.getCheckOutDate().toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String str1 = df1.format(CheckInDate);
                String str2 = df1.format(CheckOutDate);
                itripHotelOrder.setCheckInDate(str1);
                itripHotelOrder.setCheckOutDate(str2);
                //拿到酒店名称丶酒店价格丶房间数量
                StoreOrderRommHotelVo storeOrderRommHotelVo = itripHotelOrderMapper.getHotelProductStoreDic(itripHotelOrder);
                //拿到当前时间酒店已经入住的房间数量
                int count = itripHotelOrderMapper.countItripHotelOrder(itripHotelOrder);
                //判断酒店对象是否为空
                if (storeOrderRommHotelVo != null && !"".equals(storeOrderRommHotelVo)) {
                    //用房间数量减去当前房间已经入住的数量
                    storeOrderRommHotelVo.setStore(storeOrderRommHotelVo.getStore() - count);
                    return storeOrderRommHotelVo;
                }
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 新增订单
     *
     * @param orderAndLinkUserVo
     * @return
     */
    @Override
    public void addHotelOrder(OrderAndLinkUserVo orderAndLinkUserVo) {
        if (orderAndLinkUserVo != null && !"".equals(orderAndLinkUserVo)) {
            //将前台传入的时间进行转换
            //输入的被转化的时间格式
            SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);
            //需要转化成的时间格式
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date CheckInDate = null;
            Date CheckOutDate = null;
            try {
                CheckInDate = dff.parse(orderAndLinkUserVo.getCheckInDate());
                CheckOutDate = dff.parse(orderAndLinkUserVo.getCheckOutDate().toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String str1 = df1.format(CheckInDate);
            String str2 = df1.format(CheckOutDate);
            orderAndLinkUserVo.setCheckInDate(str1);
            orderAndLinkUserVo.setCheckOutDate(str2);


            Date CheckInDate1 = null;
            Date CheckOutDate1 = null;
            try {
                CheckInDate1 = df1.parse(orderAndLinkUserVo.getCheckInDate());
                CheckOutDate1 = df1.parse(orderAndLinkUserVo.getCheckOutDate().toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            //获取天数
            Long numberOfDays = (CheckOutDate1.getTime() - CheckInDate1.getTime()) / 1000;
            orderAndLinkUserVo.setBookingDays(new Long(numberOfDays / (24 * 3600)).intValue());
            //获取金额
            int count = itripHotelOrderMapper.countPayAmount(orderAndLinkUserVo);
            //将int转换成BigDecimal
            BigDecimal number;
            number = BigDecimal.valueOf((count));
            orderAndLinkUserVo.setPayAmount(number);

            //订单后面拼接时间获取订单号
            String simpleDateFormat = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            //获取6位随机数
            Integer random = (int) ((Math.random() * 9 + 1) * 100000);
            orderAndLinkUserVo.setOrderNo("D1000001" + simpleDateFormat + random);
            String linkUserName = "";
            for (int i = 0; i < orderAndLinkUserVo.getLinkUser().size(); i++) {
                linkUserName += orderAndLinkUserVo.getLinkUser().get(i).getLinkUserName();
                if (i < orderAndLinkUserVo.getLinkUser().size() - 1) {
                    linkUserName += ",";
                }
            }
            orderAndLinkUserVo.setLinkUserName(linkUserName);
            orderAndLinkUserVo.setStore(20 - orderAndLinkUserVo.getCount());


            //酒店预订
            itripHotelOrderMapper.addHotelOrder(orderAndLinkUserVo);
            //新增库存表
            itripHotelOrderMapper.addItripHotelTempStore(orderAndLinkUserVo);

            ItripHotelOrder itripHotelOrder = itripHotelOrderMapper.getItripHotelOrder(orderAndLinkUserVo.getOrderNo());

            ItripOrderLinkUser itripOrderLinkUser = new ItripOrderLinkUser();

            //新增入住用户
            for (int i = 0; i < orderAndLinkUserVo.getLinkUser().size(); i++) {
                itripOrderLinkUser.setOrderId(itripHotelOrder.getId());
                itripOrderLinkUser.setLinkUserId(orderAndLinkUserVo.getLinkUser().get(i).getId());
                itripOrderLinkUser.setLinkUserName(orderAndLinkUserVo.getLinkUser().get(i).getLinkUserName());
                itripOrderLinkUser.setCreatedBy(orderAndLinkUserVo.getCreatedBy());
                itripHotelOrderMapper.addItripOrderLinkUser(itripOrderLinkUser);
            }


        }
    }

    /**
     * 修改订单
     *
     * @param orderAndLinkUserVo
     */
    @Override
    public void updateHotelOrder(OrderAndLinkUserVo orderAndLinkUserVo) {
        if (orderAndLinkUserVo != null && !"".equals(orderAndLinkUserVo)) {

            //需要转化成的时间格式
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date CheckInDate1 = null;
            Date CheckOutDate1 = null;
            try {
                CheckInDate1 = df1.parse(orderAndLinkUserVo.getCheckInDate());
                CheckOutDate1 = df1.parse(orderAndLinkUserVo.getCheckOutDate());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //获取天数
            Long numberOfDays = (CheckOutDate1.getTime() - CheckInDate1.getTime()) / 1000;
            orderAndLinkUserVo.setBookingDays(new Long(numberOfDays / (24 * 3600)).intValue());

            //获取金额
            int count = itripHotelOrderMapper.countPayAmount(orderAndLinkUserVo);
            //将int转换成BigDecimal
            BigDecimal number;
            number = BigDecimal.valueOf((count));
            orderAndLinkUserVo.setPayAmount(number);
            String linkUserName = "";
            for (int i = 0; i < orderAndLinkUserVo.getLinkUser().size(); i++) {
                linkUserName += orderAndLinkUserVo.getLinkUser().get(i).getLinkUserName();
                if (i < orderAndLinkUserVo.getLinkUser().size() - 1) {
                    linkUserName += ",";
                }
            }
            orderAndLinkUserVo.setLinkUserName(linkUserName);
            orderAndLinkUserVo.setStore(20 - orderAndLinkUserVo.getCount());

            //修改订单
            itripHotelOrderMapper.updateHotelOrder(orderAndLinkUserVo);
            //删除用户
            itripHotelOrderMapper.deleteItripOrderLinkUser(orderAndLinkUserVo);
            //删除用户之后在拿到要更换的用户
            //新增入住用户
            ItripOrderLinkUser itripOrderLinkUser = new ItripOrderLinkUser();
            ItripHotelOrder itripHotelOrder = itripHotelOrderMapper.getItripHotelOrder(orderAndLinkUserVo.getOrderNo());
            for (int i = 0; i < orderAndLinkUserVo.getLinkUser().size(); i++) {
                itripOrderLinkUser.setOrderId(itripHotelOrder.getId());
                itripOrderLinkUser.setLinkUserId(orderAndLinkUserVo.getLinkUser().get(i).getId());
                itripOrderLinkUser.setLinkUserName(orderAndLinkUserVo.getLinkUser().get(i).getLinkUserName());
                itripOrderLinkUser.setCreatedBy(orderAndLinkUserVo.getCreatedBy());
                itripHotelOrderMapper.addItripOrderLinkUser(itripOrderLinkUser);
            }
        }
    }

    /**
     * 查询超过两个小时未支付的订单
     *
     * @return
     */
    @Scheduled(fixedRate = 600000)
    @Override
    public void listTimedTask() {
        try {
            ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
            List<ItripHotelOrder> list = itripHotelOrderMapper.listTimedTask();
            if (list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    Long id = list.get(i).getId();
                    itripHotelOrderMapper.updateTimedTask(id);
                    itripHotelOrder.setCount(list.get(i).getCount());
                    itripHotelOrder.setHotelId(list.get(i).getHotelId());
                    itripHotelOrder.setRoomId(list.get(i).getRoomId());
                    itripHotelOrder.setCheckInDate(list.get(i).getCheckInDate());
                    int store = itripHotelOrderMapper.getStore(itripHotelOrder);
                    itripHotelOrder.setStore(store);
                    itripHotelOrderMapper.updateRepertory(itripHotelOrder);
                }
            }
        }catch (Exception e){
            //数据手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

    /**
     * 查询待支付订单中 退房时间已到期的改为已消费
     *
     * @param
     */
    @Scheduled(fixedRate = 7200000)
    @Override
    public void listOrder() {
        try {
            ItripHotelOrder hotelOrder = new ItripHotelOrder();
            List<ItripHotelOrder> listOrder = itripHotelOrderMapper.listOrder();
            if (listOrder.size() != 0) {
                for (int i = 0; i < listOrder.size(); i++) {
                    hotelOrder.setId(listOrder.get(i).getId());
                    hotelOrder.setOrderNo(listOrder.get(i).getOrderNo());
                    itripHotelOrderMapper.updateOrderStatus(hotelOrder);
                }
            }
        }catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }
}